package com.ccp.learning.udp.db;

import com.ccp.learning.udp.entity.LogEntry;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class RecoveryManager {
    private static final String RECOVERY_FILE = ConfigManager.getRecoveryPath();

    public static synchronized void saveRecoveryData(List<LogEntry> data) {
        try (ObjectOutputStream oos = new ObjectOutputStream(
                new BufferedOutputStream(new FileOutputStream(RECOVERY_FILE)))) {
            oos.writeObject(data);
        } catch (IOException e) {
            System.err.println("恢复数据持久化失败: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    public static List<LogEntry> loadRecoveryData() {
        File file = new File(RECOVERY_FILE);
        if (!file.exists()) return new ArrayList<>();

        try (ObjectInputStream ois = new ObjectInputStream(
                new BufferedInputStream(new FileInputStream(file)))) {
            return (List<LogEntry>) ois.readObject();
        } catch (Exception e) {
            System.err.println("加载恢复数据失败: " + e.getMessage());
            return new ArrayList<>();
        }
    }

    public static void clearRecoveryData() {
        new File(RECOVERY_FILE).delete();
    }
}